package amq.demo.thds;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

import amq.utils.GlobalAMQ;
import amq.utils.enums.ELangCode;

public class SQThd implements Runnable, MessageListener, ExceptionListener{
	String brokerURI = null;
	public boolean isStop = false;
	//public static String topic = "NTNU.SERV";
	public Session session;
	public String serviceName=null;
	public String topic;
	public ELangCode slc;
	
	/**
	 * BD: Constructor 
	 * @param bi: Broker URI
	 * @param sn: Service Name
	 * @param topic: 
	 * @param lc: Target Language Code
	 */
	public SQThd(String bi, String sn, String topic, ELangCode lc)
	{
		this.brokerURI = bi;
		this.serviceName = sn;
		this.topic = topic;
		this.slc = lc; 				// service language code
	}

	@Override
	public void onException(JMSException expt) {
		System.err.printf("\t[%s] Exception Message:\n%s\n", serviceName, expt);			
	}

	@Override
	public void onMessage(Message msg) {
		MessageProducer producer = null;
		try
		{
			ELangCode lc = ELangCode.TS(msg.getStringProperty("LangCode")); 	// Trad,Simp,Engi etc
			if(lc!=null && !slc.equals(lc))
			{
				System.out.printf("\t[%s] Drop heart beat(%s)...\n", serviceName, lc);
				return;
			}
			String rt = msg.getStringProperty("ReplyTo"); 	// ReplyTo 
			String tid = msg.getStringProperty("TID");		// Task ID
			Destination destination = session.createQueue(rt);
			producer = session.createProducer(destination);
	        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
	        TextMessage message = session.createTextMessage(serviceName);
	        message.setStringProperty("TID", tid);
	        message.setStringProperty("LangCode", slc.toString());
	        message.setStringProperty("Topic", topic);
	        producer.send(message);
			System.out.printf("\t[%s] Heart beat check to %s!\n", serviceName, rt);
		}
		catch(JMSException e)
		{
			System.err.printf("\t[%s] Exception Message:\n%s\n", serviceName, e);
			e.printStackTrace();
		}
		finally
		{
			if(producer!=null) 
			{
				try{producer.close();}catch(Exception e){}
			}
		}
	}

	@Override
	public void run() {
		try {
			System.out.printf("\t[Info] Listening to Topic:'%s'...\n", GlobalAMQ.ServiTopic);
			// Create a ConnectionFactory
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerURI);

            // Create a Connection
            Connection connection = connectionFactory.createConnection();
            connection.start();

            connection.setExceptionListener(this);

            // Create a Session
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // Create the destination (Topic or Queue)
            Destination destination = session.createTopic(GlobalAMQ.ServiTopic);

            // Create a MessageConsumer from the Session to the Topic or Queue
            MessageConsumer consumer = session.createConsumer(destination);

            consumer.setMessageListener(this);
            while(!isStop)
            {
            	Thread.sleep(5000);
            }
            System.out.printf("\t[%s] Stop listening to Topic:'%s'...\n", serviceName, GlobalAMQ.ServiTopic);
            consumer.close();
            session.close();
            connection.close();
        }
        catch (Exception e) {
            System.out.println("Caught: " + e);
            e.printStackTrace();
        }
	}
}
